package com.ruoyi.project.inner.service.impl;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.project.common.JsonResult;
import com.ruoyi.project.inner.constant.MqttTopic;
import com.ruoyi.project.inner.dao.GardensTerminalMapper;
import com.ruoyi.project.inner.entity.GardensTerminal;
import com.ruoyi.project.inner.mqtt.constant.MqttMessageArrivedCall;

import com.ruoyi.project.inner.service.MqttService;

import com.ruoyi.project.inner.utils.MacTopicUtil;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;


/**
 * @author Squbi
 */
@Component
public class MqttCallBackService implements MqttMessageArrivedCall {
    private static final Logger LOGGER = LoggerFactory.getLogger(MqttCallBackService.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqttService template;

    @Autowired
    private GardensTerminalMapper terminalMapper;

    @Override
    public void exec(String topic, MqttMessage message) {
        if (topic.equals(MqttTopic.SERVER_TOPIC)) {
            server(message);
        } else {
            other(topic, message);
        }
    }

    private void server(MqttMessage message) {
        LOGGER.info("message from server : {}", message);
        String terminal = new String(message.getPayload());
        String mac = terminal.replaceFirst(MqttTopic.TERMINAL_ENDING, "");
        GardensTerminal gt = terminalMapper.selectOne(new QueryWrapper<GardensTerminal>().eq("terminal_mac", mac));
        if (gt == null) {
            gt = new GardensTerminal(null, mac, LocalDateTime.now());
            terminalMapper.insert(gt);
        } else {
            gt.setTerminalLastLogin(LocalDateTime.now());
            terminalMapper.updateById(gt);
        }
    }

    private void other(String topic, MqttMessage message) {
        LOGGER.info("message from `{}` topic : {}", topic, message);
        if (!topic.isEmpty() && message != null) {
            String result = new String(message.getPayload());
            JsonResult jsonResult = JSON.parseObject(result, JsonResult.class);
            String key = MacTopicUtil.getRedisKeyByTopic(topic, jsonResult.getUuid());
            LOGGER.debug(" -- redis save: {} - {}", key, result);
            redisTemplate.opsForValue().set(key, result, Duration.ofSeconds(30));
        }
    }
}
